
$(function () {
    $('#btn_save').on('click', function () {
        submitForm();
    });
    var cArr=[];
    for(var i =1;i<=10;i++){
        var y = {id:i,text:i+'年'};
        cArr.push(y);
    }
    $('#reviewCycle').combobox(
        {
            data:cArr,
            prompt:'请选择',
            valueField:'id',
            textField:'text',
            editable: false,
            onSelect:function (r) {
                var aa=$('#certificateTime').val();
                if($('#certificateTime').val()!=''){
                    var cc= AddDays(aa,r.id*365);
                    $('#nextReviewTime').datebox('setValue',cc);
                }
            }
        }
    );
    $('#certificateTime').datebox({
        onSelect: function(date){
            var dataNew= date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
            var a=$('#reviewCycle').val();
            var b=$('#changedCycle').val();
            var c=$('#isReview').val();
            var d=$('#isChanged').val();
            if(a!=''&&c=='1'){
                var cc= AddDays(dataNew,a*365);
                $('#nextReviewTime').datebox('setValue',cc);
            }
            if(b!=''&&d=='1'){
                var cc= AddDays(dataNew,b*365);
                $('#nextChangedTime').datebox('setValue',cc);
            }
        }
    });
    $('#changedCycle').combobox(
        {
            data:cArr,
            prompt:'请选择',
            valueField:'id',
            textField:'text',
            editable: false,
            onSelect:function (r) {
                var aa=$('#certificateTime').val();
                if($('#certificateTime').val()!=''){
                    var cc= AddDays(aa,r.id*365);
                    $('#nextChangedTime').datebox('setValue',cc);
                }
            }
        }
    );
    /**
     * 绑定人员选择事件
     */
    $("#userIdName").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_userId_func();
            }
        }]
    });
    var TRAIN_FZLEVEL=CONSTANT.DictionaryTypeDefConstants.TRAIN_FZLEVEL;//发证机关级别
    queryComboData(TRAIN_FZLEVEL,'authorityLevelId');
    var TRAIN_ZSTYPE=CONSTANT.DictionaryTypeDefConstants.TRAIN_ZSTYPE;//证书类型(数据字典)
    queryComboData(TRAIN_ZSTYPE,'certificateTypeId');
    var isReview=[{id:'1',text:'是'},{id:'0',text:'否'}];
    $('#isReview').combobox({
        data: isReview,
        prompt:'请选择',
        valueField: 'id',
        textField: 'text',
        editable: false,
        panelHeight: '200',
        selectOnNavigation:true,
        onSelect:function (r) {
            if(r.id=='1'){
                $('#reviewCycle').combobox('setValue','').combobox({disabled:false});
                $('#nextReviewTime').datebox('setValue','').datebox({disabled:false});
            }else{
                $('#reviewCycle').combobox('setValue','').combobox({disabled:true});
                $('#nextReviewTime').datebox('setValue','').datebox({disabled:true});
            }
        }
    });
    $('#isChanged').combobox({
        data: isReview,
        prompt:'请选择',
        valueField: 'id',
        textField: 'text',
        editable: false,
        panelHeight: '200',
        onSelect:function (r) {
            if(r.id=='1'){
                $('#changedCycle').combobox('setValue','').combobox({disabled:false});
                $('#nextChangedTime').datebox('setValue','').datebox({disabled:false});
            }else{
                $('#changedCycle').combobox('setValue','').combobox({disabled:true});
                $('#nextChangedTime').datebox('setValue','').datebox({disabled:true});
            }
        }
    });

    $("#danwei").textbox('setValue', danweiName).textbox('setText', danweiName);
    addcerTb(certificateId);
});
function AddDays(date,days){
    var nd = new Date(date);
    nd = nd.valueOf();
    nd = nd + days * 24 * 60 * 60 * 1000;
    nd = new Date(nd);
    //alert(nd.getFullYear() + "年" + (nd.getMonth() + 1) + "月" + nd.getDate() + "日");
    var y = nd.getFullYear();
    var m = nd.getMonth()+1;
    var d = nd.getDate();
    if(m <= 9) m = "0"+m;
    if(d <= 9) d = "0"+d;
    var cdate = y+"-"+m+"-"+d;
    return cdate;
}
function pageComData(id,data) {
    var pageId='#'+id;
    $(pageId).combobox({
        data: data,
        prompt:'请选择',
        valueField: 'id',
        textField: 'text',
        editable: false,
        panelHeight: '200',
        selectOnNavigation:true,
    });
}
var add_userId_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack:function(data){
            getSelectedUser(data);
        }
    });
};
/**
 * 人员信息选择
 */
var getSelectedUser = function (data) {
    if(data.length>0){
        $("#userIdName").textbox('setValue', data[0].realName).textbox('setText', data[0].realName);
        $("#userId").val(data[0].id);
        var deptName='';
        if (data[0].userDepartmentList && data[0].userDepartmentList.length > 0) {
            for (var index in data[0].userDepartmentList) {
                if (data[0].userDepartmentList[index].deptName != null) {
                    deptName += ',' + data[0].userDepartmentList[index].deptName;
                }
            }
            deptName= deptName.substring(1);
        } else {
            deptName='';
        }
        $("#danwei").textbox('setValue', deptName).textbox('setText', deptName);
        $("#gonghao").textbox('setValue', data[0].code).textbox('setText', data[0].code);
        $("#gangwei").textbox('setValue', data[0].postName).textbox('setText', data[0].postName);
    }
};

function queryComboData(code,queryId) {
    var pageId='#'+queryId;
    $.ajax({
        type: 'post',
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',
        data: {code: code},
        dataType: "json",
        success: function (result) {
            $(pageId).combobox({
                data: result,
                prompt:'请选择',
                valueField: 'id',
                textField: 'text',
                editable: false,
                panelHeight: '200'

            });
        }
    });
}

function addcerTb(certificateId) {
    //登记类型（0复审，1换证；2发证 ；3换证）
    var isHgData=[{id:'0',text:'复审'},{id:'1',text:'换证'}];
    $('#cerTb').datagrid({
        fitColumns: true,
        idField: 'id',
        rownumbers: true,
        sortOrder: true,
        singleSelect: true,
        striped: true,
        fit: false,
        url:ROOT_PATH + '/train/certificate/selectRecords.shtml',
        height: 300,
        queryParams: {
            certificateId: certificateId,
        },
        columns: [[
            {
                field: 'id', title: 'id', hidden:true,width: 20
            },
            {
                field: 'certificateId', title: 'certificateId', hidden:true,width: 20
            },
            {field: 'recordType', title: '登记种类', width: 100,
                formatter: function (value, row, index){
                    return row.recordType=='2'?'发证':(row.recordType=='0'?'复审':'换证');
                },
                editor: {
                    type: 'combobox',
                    options: {
                        data: isHgData,
                        valueField: 'id',
                        editable:false,
                        textField: 'text',
                        required: true,
                        panelHeight: '60',
                        loadFilter:function(data){
                            var newData = new Array();
                            if ($("#isReview").val()=='1'){
                                newData.push({id:"0",text:'复审'});
                            }
                            if($("#isChanged").val()=='1'){
                                newData.push({id:"1",text:'换证'});
                            }
                            return newData;
                        }
                    }
                }},
            {field: 'certificateCode', title: '证书编号', width: 100,editor: {type: 'textbox', options:{ onChange:function (newValue, oldValue) {
                $("#num").textbox('setValue', newValue);
                certificateCode=newValue;
            } }}},
            {field: 'time', title: '发证/复审/换证日期', width: 100,editor: {type: 'datebox',
                options: {
                    required: true,
                    editable:false,
                    onSelect: function(date){
                        var dataNew= date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
                        $('#certificateTime').datebox('setValue',dataNew);
                        var a=$('#reviewCycle').val();
                        var b=$('#changedCycle').val();
                        var c=$('#isReview').val();
                        var d=$('#isChanged').val();
                        var ed = $("#cerTb").datagrid('getEditor', { index: editIndex_cerTb, field: 'nextTime' });
                        if(a!=''&&c=='1'){
                            var cc= AddDays(dataNew,a*365);
                            $('#nextReviewTime').datebox('setValue',cc);
                            $(ed.target).datebox('setValue',cc);
                        }
                        if(b!=''&&d=='1'){
                            var cc= AddDays(dataNew,b*365);
                            $('#nextChangedTime').datebox('setValue',cc);
                            $(ed.target).datebox('setValue',cc);
                        }
                    }
                }
            }},
            {field: 'nextTime',title: '下次复审/换证日期', width: 100,editor: {type: 'datebox',
                options: {required: true,
                    editable:false,
                    onSelect: function(date){
                        var dataNew= date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
                        var c=$('#isReview').val();
                        var d=$('#isChanged').val();
                        if(c=='1'){
                            $('#nextReviewTime').datebox('setValue',dataNew);
                        }
                        if(d=='1'){
                            $('#nextChangedTime').datebox('setValue',dataNew);
                        }
                    }
                }
            }},

            {field: 'addUserName', title: '登记人', width: 100},
            {field: 'addDeptName', title: '登记部门', width: 100},
            {field: 'addTime', title: '登记日期', width: 100},
        ]],
        onClickRow:function (index, row) {
            if (editIndex_cerTb != index){
                if (endEditingRtb()&&row.recordType!='2'){
                    $('#cerTb').datagrid('selectRow', index).datagrid('beginEdit', index);
                    editIndex_cerTb = index;
                }else {
                    $('#cerTb').datagrid('selectRow', editIndex_cerTb);
                }
            }
        }
    });
    $('#cerTb_save').on('click', function () {
        if (endEditingRtb()){
        }
    });
    $('#cerTb_add').on('click', function () {
        if($("#isReview").val()!='1'&&$("#isChanged").val()!=1){
            layer.alert("不复审或换证时无需添加记录！");
            return;
        }
        if (endEditingRtb()){
            $('#cerTb').datagrid('appendRow',{
                certificateId: $("#id").val(),
                certificateCode:certificateCode
            });
            editIndex_cerTb = $('#cerTb').datagrid('getRows').length-1;
            $('#cerTb').datagrid('selectRow', editIndex_cerTb).datagrid('beginEdit', editIndex_cerTb);
        }
    });
    $('#cerTb_remove').on('click', function () {
        if (editIndex_cerTb == undefined){return}
        $('#cerTb').datagrid('cancelEdit', editIndex_cerTb).datagrid('deleteRow', editIndex_cerTb);
        editIndex_cerTb = undefined;
    });
}
var editIndex_cerTb = undefined;
function endEditingRtb(){
    if (editIndex_cerTb == undefined){return true}
    if ($('#cerTb').datagrid('validateRow', editIndex_cerTb)){
        $('#cerTb').datagrid('endEdit', editIndex_cerTb);
        editIndex_cerTb = undefined;
        return true;
    } else {
        return false;
    }
}
function submitForm() {
    if (!$('#formCeData').form('validate')) { layer.alert("请正确填写信息"); return $('#formReData').form('validate');}
    var objParams = $('#formCeData').serializeJson();
    var objArr1=$('#cerTb').datagrid('getData');
    if(objArr1.total>0){
        var cerTb= JSON.stringify(objArr1.rows);
        objParams.cerTb=cerTb;
    }
    $.ajax({
        url:ROOT_PATH + '/train/certificate/updateData.shtml',//提交地址
        data:objParams,
        type:"POST",
        dataType:"json",
        success: function (result) {
            if (result.success) {
                layer.msg('保存成功', {
                    icon: 1,
                    time: 1000
                }, function () {
                    WindowManager.closeLayer({
                        returnValue: true
                    });
                });
            }
            else {
                layer.msg('保存失败', {
                    icon: 2,
                    time: 1000
                });
            }
        }
    });
}